package com.yuqih.common.servlet;

import java.net.URL;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.yuqih.common.exception.CodedException;
import com.yuqih.common.net.IpUtils;


public class RequestUtil {
	
	private static final Log logger = LogFactory.getLog(RequestUtil.class);

	/**
	 * @param referrer
	 * @return
	 */
	public static String getHostByReferrer(String referrer) {
		if (StringUtils.isBlank(referrer)) {
			return null;
		}

		URL url;
		try {
			url = new URL(referrer);
		} catch (Exception e) {
			logger.error("获取请求url对应域名出错");
			throw CodedException.from(e);
		}
		return url.getHost();
	}

	/**
	 * header的一般顺序:
	 * <li>X-Real-IP</li>
	 * <li>X-Forwarded-For</li>
	 * <li>Proxy-Client-IP</li>
	 * <li>WL-Proxy-Client-IP</li>
	 * <li>HTTP_CLIENT_IP</li>
	 * <li>HTTP_X_FORWARDED_FOR</li>
	 * <li></li>
	 * 
	 * @param request
	 * @return 请求IP地址
	 */
	public static String getRemoteIp(HttpServletRequest request, String[] headerNames) {
		if (headerNames == null) {
			return request.getRemoteAddr();
		}
		
		String ipHeader = null;
		String ip = null;
		String headerName = null;
		for (int i = 0; i < headerNames.length; i++) {
			headerName = headerNames[i];
			ipHeader = request.getHeader(headerName);
			ip = IpUtils.getHttpRemoteIp(ipHeader);
			if (ip != null) {
				return ip;
			}
		}

		return request.getRemoteAddr();

	}

}
